<template>
  <n-upload
    v-model:file-list="fileList"
    :customRequest="customRequest"
    :max="1"
    @before-upload="beforeUpload"
    @finish="finishChange"
    @remove="handDel"
  >
    <div class="flex align-center">
      <n-button class="btn" type="primary">
        <i class="landscape landscape-shangchuan"></i>
        <span>选择文件</span>
      </n-button>
    </div>
  </n-upload>
</template>
<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { NButton, NUpload, useMessage } from 'naive-ui'
import type { UploadFileInfo, UploadCustomRequestOptions } from 'naive-ui'
import systemApi from '@/service/api/system'
type PropsState = {
  modelValue: string
}
const props = withDefaults(defineProps<PropsState>(), {
  modelValue: ''
})
const emit = defineEmits(['update:modelValue'])
const fileList = ref<UploadFileInfo[]>([])

watchEffect(() => {
  if (props.modelValue && fileList.value.length === 0) {
    const arr = props.modelValue.split('/')
    fileList.value = [
      {
        id: props.modelValue,
        name: arr[arr.length - 1],
        url: props.modelValue,
        thumbnailUrl: props.modelValue,
        status: 'finished'
      }
    ]
  }
})
const customRequest = (options: UploadCustomRequestOptions) => {
  const params: any = new FormData()
  params.append('file', options.file.file)
  systemApi.upload(params).then(({ data }) => {
    options.file.thumbnailUrl = data.url
    options.file.url = data.url
    options.onFinish()
  })
}
const toast = useMessage()
const beforeUpload = async (data: {
  file: UploadFileInfo
  fileList: UploadFileInfo[]
}) => {
  if (data.file.file?.size && data.file.file.size >= 50 * 1024 * 1024) {
    toast.error('上传文件大小不能超过' + 50 + 'MB，请重新上传')
    return false
  }
  return true
}

const finishChange = (e: any) => {
  emit('update:modelValue', e.file.url)
}
const handDel = () => {
  emit('update:modelValue', '')
}
</script>
<style scoped lang="scss"></style>
